<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta charset="UTF-8" />
    <title>知识库文件管理</title>
    <!-- 引入Bootstrap -->
    <link
      href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/js/bootstrap.bundle.min.js"></script>
    <style>
      .container {
        padding: 20px;
      }
      .table-responsive {
        margin-top: 20px;
      }
      .action-buttons {
        white-space: nowrap;
      }
      .search-bar {
        margin-bottom: 15px;
        display: flex;
        align-items: center;
        gap: 0.5rem;
      }
      .search-bar .form-control,
      .search-bar .form-select,
      .search-bar .btn {
        height: 35px;
        padding-top: 0.25rem;
        padding-bottom: 0.25rem;
      }
      .search-bar .btn {
        width: 300px;
      }
      .file-type {
        width: 200px;
      }
    </style>
  </head>
  <body th:fragment="content">
    <div class="container">
      <div class="d-flex justify-content-between align-items-center">
        <h2>知识库文件管理</h2>
        <button class="btn btn-primary" onclick="showUploadModal()">
          上传文件
        </button>
      </div>

      <!-- 搜索栏 -->
      <div class="search-bar d-flex gap-2">
        <input
          type="text"
          class="form-control"
          id="searchInput"
          placeholder="请输入文件名"
        />
        <select class="form-select file-type" id="fileType">
          <option value="">请选择文件类型</option>
          <option value="txt">TXT</option>
          <option value="docx">DOCX</option>
          <option value="md">MD</option>
        </select>
        <select class="form-select file-type" id="knowledgeId">
          <option value="">请选择知识库</option>
        </select>
        <button class="btn btn-primary" onclick="searchFiles()">搜索</button>
        <button class="btn btn-secondary" onclick="resetSearch()">重置</button>
      </div>

      <div class="table-responsive">
        <table class="table table-striped">
          <thead>
            <tr>
              <th>#</th>
              <th>名称</th>
              <th>文件类型</th>
              <th>文件来源</th>
              <th>切片状态</th>
              <th>切片数量</th>
              <th>命中次数</th>
              <!--              <th>切片结果</th>-->
              <!--              <th>总结结果</th>-->
              <th>操作</th>
            </tr>
          </thead>
          <tbody id="fileList">
            <!-- 数据将通过JavaScript动态加载 -->
          </tbody>
        </table>
        <!-- 分页控件 -->
        <nav aria-label="Page navigation">
          <ul class="pagination justify-content-end" id="pagination"></ul>
        </nav>
      </div>
    </div>

    <!-- 上传文件模态框 -->
    <div class="modal fade" id="uploadModal" tabindex="-1">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">上传文件</h5>
            <button
              type="button"
              class="btn-close"
              data-bs-dismiss="modal"
            ></button>
          </div>
          <div class="modal-body">
            <form id="uploadForm">
              <div class="mb-3">
                <label for="knowledgeId" class="form-label">选择知识库</label>
                <select class="form-select" id="knowledgeRepo" required>
                  <option value="">请选择知识库</option>
                </select>
              </div>
              <div class="mb-3">
                <label for="file" class="form-label">选择文件</label>
                <input type="file" class="form-control" id="file" required />
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-secondary"
              data-bs-dismiss="modal"
            >
              取消
            </button>
            <button
              type="button"
              class="btn btn-primary"
              onclick="uploadFile()"
            >
              上传
            </button>
          </div>
        </div>
      </div>
    </div>

    <script>
      let currentPage = 1;
      let pageSize = 10;
      let totalPages = 0;

      // 页面加载完成后获取文件列表
      $(document).ready(function () {
        loadFileList(1);
      });

      // 加载文件列表
      function loadFileList(pageNo) {
        currentPage = pageNo;
        const searchParams = [];

        // 只有当输入框有值时才添加搜索条件
        const fileName = $('#searchInput').val();
        if (fileName) {
          searchParams.push({
            column: 'fileName',
            operator: 'LIKE',
            value: fileName
          });
        }

        const fileType = $('#fileType').val();
        if (fileType) {
          searchParams.push({
            column: 'fileType',
            operator: 'EQ',
            value: fileType
          });
        }

        const knowledgeId = $('#knowledgeId').val();
        if (knowledgeId) {
          searchParams.push({
            column: 'knowledge_id',
            operator: 'EQ',
            value: knowledgeId
          });
        }

        $.ajax({
          url: '/knowledge/file/tables',
          method: 'POST',
          contentType: 'application/json',
          data: JSON.stringify({
            pageNo: pageNo,
            pageSize: pageSize,
            searchParams: searchParams,
            sortOptions: []
          }),
          success: function (response) {
            if (response.code === 200) {
              const data = response.data;
              let html = '';
              data.records.forEach(function (item) {
                html += `
                        <tr>
                          <td>${item.id}</td>
                          <td>${item.name}</td>
                          <td>${item.fileType}</td>
                          <td>${item.source}</td>
                          <td>
                            ${getSliceStatusText(item.sliceResult)}
                          </td>
                          <td>${item.sliceCount}</td>
                          <td>${item.hitCount}</td>
                          <!--<td>
                            <button class="btn btn-sm btn-info" onclick="viewSlices(${
                              item.id
                            })">已切片</button>
                          </td>
                          <td>
                            <button class="btn btn-sm btn-info" onclick="viewSummary(${
                              item.id
                            })">已总结</button>
                          </td> -->
                          <td class="action-buttons">
                           <button class="btn btn-sm btn-danger" onclick="splitFile(${
                             item.id
                           })">切片</button>
                            <button class="btn btn-sm btn-danger" onclick="deleteFile(${
                              item.id
                            })">删除</button>
                          </td>
                        </tr>
                      `;
              });
              $('#fileList').html(html);

              // 更新分页信息
              totalPages = data.pages;
              updatePagination();
            } else {
              alert('加载失败：' + response.message);
            }
          },
          error: function (xhr) {
            alert('加载文件列表失败：' + xhr.responseText);
          }
        });
      }

      function splitFile(id) {
        $.ajax({
          url: '/knowledge/file/splitFile/' + id,
          method: 'POST',
          success: function (response) {
            if (response.code === 200) {
              alert('切片成功');
              loadFileList(currentPage);
            } else {
              alert('切片失败：' + response.message);
            }
          },
          error: function (xhr) {
            alert('切片失败：' + xhr.responseText);
          }
        });
      }

      // 更新分页控件
      function updatePagination() {
        let paginationHtml = '';

        if (totalPages === 0) {
          $('#pagination').html('');
          return;
        }

        // 上一页按钮
        paginationHtml += `
                <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                  <a class="page-link" href="javascript:void(0)" onclick="loadFileList(${
                    currentPage - 1
                  })" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                  </a>
                </li>
              `;

        // 页码按钮
        const maxVisiblePages = 5;
        let startPage = Math.max(
          1,
          currentPage - Math.floor(maxVisiblePages / 2)
        );
        let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

        if (endPage - startPage + 1 < maxVisiblePages) {
          startPage = Math.max(1, endPage - maxVisiblePages + 1);
        }

        if (startPage > 1) {
          paginationHtml += `
                  <li class="page-item">
                    <a class="page-link" href="javascript:void(0)" onclick="loadFileList(1)">1</a>
                  </li>
                `;
          if (startPage > 2) {
            paginationHtml += `
                    <li class="page-item disabled">
                      <span class="page-link">...</span>
                    </li>
                  `;
          }
        }

        for (let i = startPage; i <= endPage; i++) {
          paginationHtml += `
                  <li class="page-item ${currentPage === i ? 'active' : ''}">
                    <a class="page-link" href="javascript:void(0)" onclick="loadFileList(${i})">${i}</a>
                  </li>
                `;
        }

        if (endPage < totalPages) {
          if (endPage < totalPages - 1) {
            paginationHtml += `
                    <li class="page-item disabled">
                      <span class="page-link">...</span>
                    </li>
                  `;
          }
          paginationHtml += `
                  <li class="page-item">
                    <a class="page-link" href="javascript:void(0)" onclick="loadFileList(${totalPages})">${totalPages}</a>
                  </li>
                `;
        }

        // 下一页按钮
        paginationHtml += `
                <li class="page-item ${
                  currentPage === totalPages ? 'disabled' : ''
                }">
                  <a class="page-link" href="javascript:void(0)" onclick="loadFileList(${
                    currentPage + 1
                  })" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                  </a>
                </li>
              `;

        $('#pagination').html(paginationHtml);
      }

      // 显示上传模态框
      function showUploadModal() {
        $('#uploadModal').modal('show');
      }

      // 上传文件
      // 在页面加载完成后获取知识库列表
      $(document).ready(function () {
        loadFileList(1);
        loadKnowledgeList();
      });

      // 加载知识库列表
      function loadKnowledgeList() {
        $.ajax({
          url: '/knowledge/list',
          method: 'POST',
          contentType: 'application/json',
          data: JSON.stringify({
            pageNo: 1,
            pageSize: 1000,
            searchParams: [],
            sortOptions: []
          }),
          success: function (response) {
            if (response.code === 200) {
              const data = response.data;
              let html = '<option value="">请选择知识库</option>';
              data.forEach(function (item) {
                html += `<option value="${item.id}">${item.name}</option>`;
              });
              $('#knowledgeRepo').html(html);
              $('#knowledgeId').html(html);
            } else {
              alert('加载知识库列表失败：' + response.message);
            }
          },
          error: function (xhr) {
            alert('加载知识库列表失败：' + xhr.responseText);
          }
        });
      }

      // 修改上传文件方法
      function uploadFile() {
        const knowledgeRepo = $('#knowledgeRepo').val();
        if (!knowledgeRepo) {
          alert('请选择知识库');
          return;
        }

        const formData = new FormData();
        const fileInput = document.getElementById('file');
        formData.append('file', fileInput.files[0]);
        formData.append('knowledgeId', knowledgeRepo);

        $.ajax({
          url: '/knowledge/file/upload',
          method: 'POST',
          data: formData,
          processData: false,
          contentType: false,
          success: function (response) {
            if (response.code === 200) {
              $('#uploadModal').modal('hide');
              loadFileList(currentPage);
              alert('上传成功');
            } else {
              alert('上传失败：' + response.message);
            }
          },
          error: function (xhr) {
            alert('上传失败：' + xhr.responseText);
          }
        });
      }

      // 搜索文件
      function searchFiles() {
        loadFileList(1);
      }

      // 重置搜索
      function resetSearch() {
        $('#searchInput').val('');
        $('#fileType').val('');
        $('#knowledgeId').val('');
        loadFileList(1);
      }

      // 查看切片
      function viewSlices(id) {
        // TODO: 实现查看切片功能
        alert('查看切片功能待实现');
      }

      // 查看总结
      function viewSummary(id) {
        // TODO: 实现查看总结功能
        alert('查看总结功能待实现');
      }

      // 删除文件
      function deleteFile(id) {
        if (confirm('确定要删除这个文件吗？')) {
          $.ajax({
            url: '/knowledge/file/delete',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
              ids: [id]
            }),
            success: function (response) {
              if (response.code === 200) {
                loadFileList(currentPage);
                alert('删除成功');
              } else {
                alert('删除失败：' + response.message);
              }
            },
            error: function (xhr) {
              alert('删除失败：' + xhr.responseText);
            }
          });
        }
      }
      // 获取切片状态文本

      function getSliceStatusText(status) {
        switch (status) {
          case 0:
            return '<span class="badge bg-secondary">未切片</span>';
          case 1:
            return '<span class="badge bg-warning">切片中</span>';
          case 2:
            return '<span class="badge bg-success">已切片</span>';
          case 3:
            return '<span class="badge bg-danger">失败</span>';
          default:
            return '<span class="badge bg-secondary">未知</span>';
        }
      }
    </script>
  </body>
</html>
